import React, { useState } from 'react';
import { Modal, Form, Row, Col, Input, Tooltip, Button } from 'antd';
import { FormInstance } from 'antd/es/form/Form';
import { CopyOutlined } from '@ant-design/icons';
import ASelect from '@/components/SelfComp/ASelect';
import ACrontab from '@/components/SelfComp/ACrontab';
import { DataItem, FormModalProps } from '@/types/global';
import { JobItem } from '@/types/schedule';
import { formLayout, basicFormItemLangLayout } from '@/utils/commons';

type UpdateJobProps<T> = FormModalProps<T> & {
  jobStatusData: DataItem[];
  jobConcurrentData: DataItem[];
  jobMisfirePolicyData: DataItem[];
  flag: string;
}

const FormItem = Form.Item;

const UpdateJobModal: React.FC<UpdateJobProps<JobItem>>  = (props) => {
  /** 是否弹窗 */
  const [modalOpen, setModalOpen] = useState<boolean>(false);
  /** cron表达式 */
  const [cronExpression, setCronExpression] = useState<string>('');
  const formRef = React.createRef<FormInstance>();

  const onOk = () => {
    const { formData, flag } = props;
    if (flag === 'view') {
      const { onHandlerOK } = props;
      if (onHandlerOK) {
        onHandlerOK(formData);
      }
    } else {
      const { jobId } = formData;
      formRef.current!.validateFields().then(fieldsValue => {
        console.info(fieldsValue);
        const values = {
          ...fieldsValue,
          jobId
        };
        console.log('Received values of form: ', values);
        const { onHandlerOK } = props;
        if (onHandlerOK) {
          onHandlerOK({
            ...values
          });
        }
      }).catch((err) => console.info('表单校验不通过'));
    }
  };

  const onCancel = () => {
    // 先清除form表单
    formRef.current!.resetFields();
    const {onHandlerCancel} = props;
    if (onHandlerCancel) {
      onHandlerCancel();
    }
  }

  const openCronModal = () => {
    // 获取cron时间表达式栏位的值
    const cronExpression = formRef.current!.getFieldValue('cronExpression');
    setModalOpen(true);
    setCronExpression(cronExpression);
  }

  /**
   * Cron时间表达式生成组件确定事件，拿到组件生成的表达式，同时关闭弹窗
   * @param {*} cronStr 组件生成的表达式
   */
  const handleACrontabOk = (cronStr: string) => {
    setModalOpen(false);
    setCronExpression(cronStr);
    formRef.current!.setFieldValue('cronExpression', cronStr);
  };

  /**
   * Cron时间表达式生成组件取消事件，关闭弹窗
   */
  const handleACrontabCancel = () => {
    setModalOpen(false);
  };

  const { formData, colon, modalWidth, modalVisible, loading, flag } = props;
  const { jobStatusData, jobConcurrentData, jobMisfirePolicyData } = props;
  const formItemLayout = basicFormItemLangLayout;
  const modalTitle = (flag === 'edit' ? '修改定时任务' : '查看定时任务信息');
  // cron时间表达式栏位必输时，栏位样式设置，与antd form的样式一致
  const cronFieldRequiredLabel = (
    <>
      <span
        style={{
          color: '#ff4d4f',
          marginRight: '4px',
          fontSize: '14px',
          fontFamily: 'SimSun, sans-serif',
          lineHeight: '1'
        }}
      >
        *
      </span>
      <span>Cron时间表达式</span>
    </>
  );

  return (
    <Modal
      title={modalTitle}
      destroyOnClose
      maskClosable={false}
      width={modalWidth}
      open={modalVisible}
      confirmLoading={loading}
      onOk={onOk}
      onCancel={onCancel}>
      <Form layout={formLayout} ref={formRef}>
        <Row>
          <Col span={12}>
            <FormItem label='任务分组' name='jobGroup' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '任务分组必输' }
              ]}
              initialValue={formData.jobGroup}
            >
              <Input disabled/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='任务名称' name='jobName' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '任务名称必输' }
              ]}
              initialValue={formData.jobName}
            >
              <Input disabled/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='任务执行bean' name='invokeTarget' {...formItemLayout} colon={colon}
              rules={[
                { max: 50, message: '任务执行类最多允许输入50个字符' },
                { required: true, message: '任务执行类必输' }
              ]}
              initialValue={formData.invokeTarget}
            >
              <Input />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='任务描述' name='jobDesc' {...formItemLayout} colon={colon}
              rules={[
                { max: 50, message: '任务描述最多允许输入50个字符' },
                { required: true, message: '任务描述必输' }
              ]}
              initialValue={formData.jobDesc}
            >
              <Input />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label={cronFieldRequiredLabel} {...formItemLayout} colon={colon}
              tooltip='可点击按钮生成Cron时间表达式'
              rules={[
                { required: true }
              ]}
            >
              <Input.Group compact>
                <Form.Item name="cronExpression" noStyle
                  rules={[
                    { required: true, message: 'Cron时间表达式必输' }
                  ]}
                  initialValue={formData.cronExpression}
                >
                  <Input
                    style={{
                      width: 'calc(100% - 32px)',
                    }}
                    placeholder='请输入Cron时间表达式'
                  />
                </Form.Item>
                <Tooltip title='点击按钮生成Cron时间表达式'>
                  <Button icon={<CopyOutlined />} onClick={() => openCronModal()} />
                </Tooltip>
              </Input.Group>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="任务状态" name='jobStatus' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '任务状态必输' }
              ]}
              initialValue={formData.jobStatus}
            >
              <ASelect dataSource={jobStatusData} />
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label="是否允许并发执行" name='concurrent' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '是否允许并发执行必输' }
              ]}
              initialValue={formData.concurrent}
            >
              <ASelect dataSource={jobConcurrentData} disabled/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label="misfire处理策略" name='misfirePolicy' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: 'misfire处理策略必输' }
              ]}
              initialValue={formData.misfirePolicy}
            >
              <ASelect dataSource={jobMisfirePolicyData} disabled/>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <FormItem label='触发器分组' name='triggerGroup' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '触发器分组必输' }
              ]}
              initialValue={formData.triggerGroup}
            >
              <Input placeholder='默认与任务分组相同' disabled/>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem label='触发器名称' name='triggerName' {...formItemLayout} colon={colon}
              rules={[
                { required: true, message: '触发器名称必输' }
              ]}
              initialValue={formData.triggerName}
            >
              <Input placeholder='默认与任务名称相同' disabled/>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <ACrontab
        modalOpen={modalOpen}
        cronExpression={cronExpression}
        onHandlerOK={handleACrontabOk}
        onHandlerCancel={handleACrontabCancel}
      />
    </Modal>
  );
}

export default UpdateJobModal